<template>
  <el-container class="staff-layout">
    <!-- 侧边栏 -->
    <el-aside width="240px" class="sidebar">
      <div class="system-title">
        <span class="system-name">教职工信息管理系统</span>
      </div>

      <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
          router
      >
        <el-menu-item index="/staff">
          <el-icon><House /></el-icon>
          <span>首页</span>
        </el-menu-item>

        <el-menu-item index="/staff/teaching-projects">
          <el-icon><Reading /></el-icon>
          <span>教学项目</span>
        </el-menu-item>

        <el-menu-item index="/staff/research-projects">
          <el-icon><Document /></el-icon>
          <span>科研项目</span>
        </el-menu-item>

        <el-menu-item index="/staff/awards">
          <el-icon><Trophy /></el-icon>
          <span>奖项信息</span>
        </el-menu-item>

        <el-menu-item index="/staff/honors">
          <el-icon><Trophy /></el-icon>
          <span>人才与荣誉</span>
        </el-menu-item>


        <el-menu-item index="/staff/academic-achievements">
          <el-icon><Document /></el-icon>
          <span>学术成果</span>
        </el-menu-item>

        <el-menu-item index="/staff/activities">
          <el-icon><Calendar /></el-icon>
          <span>学术活动</span>
        </el-menu-item>

        <el-menu-item index="/staff/academic-positions">
          <el-icon><Document /></el-icon>
          <span>学术兼职</span>
        </el-menu-item>

        <el-menu-item index="/staff/social-services">
          <el-icon><Document /></el-icon>
          <span>社会服务</span>
        </el-menu-item>

        <el-menu-item index="/staff/service-contribution">
          <el-icon><Document /></el-icon>
          <span>服务贡献</span>
        </el-menu-item>

        <el-menu-item index="/staff/textbooks">
          <el-icon><Document /></el-icon>
          <span>教材/专著</span>
        </el-menu-item>


        <el-menu-item index="/staff/student-guidance">
          <el-icon><Document /></el-icon>
          <span>人才培养</span>
        </el-menu-item>

        <el-menu-item index="/staff/course-hours">
          <el-icon><Clock /></el-icon>
          <span>教学课时</span>
        </el-menu-item>

        <el-menu-item index="/staff/party-building">
          <el-icon><Flag /></el-icon>
          <span>党建工作</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/staff' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentRouteName">{{ currentRouteName }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="header-right">
          <!-- 用户信息下拉菜单 -->
          <el-dropdown @command="handleUserMenuCommand" class="user-dropdown">
            <div class="user-info">
              <el-avatar :size="32" class="user-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ userStore.userName }}</span>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="password">
                  <el-icon><Lock /></el-icon>
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item divided command="settings">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主要内容 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>

    

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="500px">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="原密码">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordChange">确定</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'  // ✅ 修复导入
import { ElMessage, ElMessageBox } from 'element-plus'
import { changePassword } from '@/api/auth'
import {
  House, Reading, Document, Trophy, Calendar, ChatDotRound, Clock, Flag,
  Bell, User, Lock, Setting, SwitchButton, ArrowDown
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()  // ✅ 修复变量名

// 响应式数据
const showPasswordDialog = ref(false)

// 密码修改表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性
const activeMenu = computed(() => route.path)
const currentRouteName = computed(() => {
  const routeNames = {
    '/staff': '首页',
    '/staff/teaching-projects': '教学项目',
    '/staff/research-projects': '科研项目',
    '/staff/awards': '奖项信息',
    '/staff/activities': '学术活动',
    '/staff/academic-positions': '学术兼职',
    '/staff/social-services': '社会服务',
    '/staff/textbooks': '教材/专著',
    '/staff/student-guidance': '指导学生',
    '/staff/course-hours': '课时统计',
    '/staff/party-building': '党建工作'
  }
  return routeNames[route.path] || ''
})

// 方法
const handleUserMenuCommand = (command) => {
  switch (command) {
    case 'password':
      showPasswordDialog.value = true
      break
    case 'settings':
      ElMessage.info('系统设置功能开发中...')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      type: 'warning'
    })

    userStore.logout()  // ✅ 修复方法调用
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch {
    // 用户取消
  }
}

const handlePasswordChange = async () => {
  if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword || !passwordForm.value.confirmPassword) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  if (passwordForm.value.oldPassword === passwordForm.value.newPassword) {
    ElMessage.error('新密码不能与原密码相同')
    return
  }

  try {
    await ElMessageBox.confirm('修改密码后需要重新登录，确定要继续吗？', '确认修改', {
      confirmButtonText: '确定修改',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await changePassword({ oldPassword: passwordForm.value.oldPassword, newPassword: passwordForm.value.newPassword })
    ElMessage.success('密码修改成功，请重新登录')
    showPasswordDialog.value = false

    // 重置表单
    passwordForm.value = { oldPassword: '', newPassword: '', confirmPassword: '' }

    // 触发退出登录
    userStore.logout()
    router.push('/login')
  } catch (err) {
    if (err !== 'cancel') {
      const status = err?.response?.status
      const serverMessage = err?.response?.data?.message || err?.response?.data || err?.message
      if (status === 400 || status === 422 || String(serverMessage || '').includes('旧密码') || String(serverMessage || '').includes('当前密码')) {
        ElMessage.closeAll()
        ElMessage.error('当前密码不正确')
      } else {
        ElMessage.error(typeof serverMessage === 'string' ? serverMessage : '修改密码失败')
      }
    }
  }
}

onMounted(() => {
  // 可以在这里加载用户信息
  console.log('StaffLayout 已加载，当前用户：', userStore.userName)
})
</script>

<style scoped>
.staff-layout {
  height: 100vh;
}

.sidebar {
  background-color: #545c64;
  overflow-y: auto;
}

.system-title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 16px;
  color: white;
  border-bottom: 1px solid #434a50;
}

.system-name {
  font-size: 16px;
  font-weight: 500;
  text-align: center;
}

.sidebar-menu {
  border-right: none;
}

.sidebar-menu .el-menu-item {
  height: 48px;
  line-height: 48px;
}

.header {
  background-color: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}


.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  border: 2px solid #e4e7ed;
}

.username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.dropdown-icon {
  color: #909399;
  transition: transform 0.3s;
}

.user-info:hover .dropdown-icon {
  transform: rotate(180deg);
}

.main-content {
  padding: 24px;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.profile-content {
  padding: 20px 0;
}
</style>